<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="班级编号" prop="id">
            <el-input v-model="queryParams.id" placeholder="请输入班级编号" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="班级名称" prop="className">
            <el-input v-model="queryParams.className" placeholder="请输入班级名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="年级" prop="grade">
            <el-input v-model="queryParams.grade" placeholder="请输入年级" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="开始年度" prop="startYear">
            <el-input v-model="queryParams.startYear" placeholder="请输入开始年度" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
         
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
             <el-button type="primary" @click="handleAdd()" v-hasPermi="['core:classes:add']">新增</el-button>
             <el-button type="primary" @click="handleImport" >导入</el-button>
             <el-button type="primary" @click="handleExport" v-hasPermi="['core:classes:export']">导出</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
        <template #header>
       <h2>班级列表</h2>
      </template>

      <el-table v-loading="loading" :data="classesList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="班级编号" align="center" prop="id" v-if="true" />
        <el-table-column label="班级名称" align="center" prop="className" />
        <el-table-column label="年级" align="center" prop="grade" >
          <template #default="scope">
            <dict-tag :options="sys_grade" :value="scope.row.grade" />
          </template>
        </el-table-column>
        <el-table-column label="开始年度" align="center" prop="startYear" />
        <el-table-column label="学校" align="center" prop="deptId" >
          <template #default="scope">
            {{getTenantById(tenantOptions,scope.row.deptId)}}
          </template>
        </el-table-column>
        <el-table-column label="学生数量" align="center" prop="" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
          <template #default="scope">
              <el-button link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['core:classes:edit']">编辑</el-button>
              <el-button link type="primary" @click="handleDelete(scope.row)" v-hasPermi="['core:classes:remove']">删除</el-button>

          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-show="total>0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
      />
    </el-card>
    <!-- 添加或修改班级管理对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="classesFormRef" :model="form" :rules="rules" label-width="100px">
         <el-form-item label="学校" prop="deptId" v-if="userId === 1 && tenantDisabled">
          <!-- <el-tree-select
                 clearable
                 filterable
                v-model="form.deptId"
                :data="deptOptions"
                :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
                value-key="deptId"
                placeholder="请选择学校"
                 :render-after-expand="false"
                
              /> -->
          <el-select v-model="form.deptId" placeholder="请选择学校" >
            <el-option v-for="item in tenantOptions" :key="item.tenantId" :label="item.companyName" :value="item.tenantId"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <!-- <el-input v-model="form.grade" placeholder="请输入年级" /> -->
         <el-select v-model="form.grade"  placeholder="请输入年级" >
            <el-option v-for="dict in sys_grade" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始年度" prop="startYear">
          <el-input v-model="form.startYear" placeholder="请输入开始年度" />
        </el-form-item>
        <el-form-item label="班级名称" prop="className">
          <el-input v-model="form.className" placeholder="请输入班级名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 用户导入对话框 -->
    <el-dialog v-model="upload.open" :title="upload.title" width="400px" append-to-body>
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload">
          <i-ep-upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="text-center el-upload__tip">
            <div class="el-upload__tip"><el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据</div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <!-- <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">下载模板</el-link> -->
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Classes" lang="ts">
import { listClasses, getClasses, delClasses, addClasses, updateClasses } from '@/api/core/classes';
import { ClassesVO, ClassesQuery, ClassesForm } from '@/api/core/classes/types';
import { globalHeaders } from '@/utils/request';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_grade } = toRefs<any>(proxy?.useDict('sys_common_status', 'sys_normal_disable','sys_grade'));
const classesList = ref<ClassesVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const classesFormRef = ref<ElFormInstance>();
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
import { getSubjectNameById,getTeacherNameById,getTenantById } from '@/utils/index';
/*** 用户导入参数 */
const upload = reactive<ImportOption>({
  // 是否显示弹出层
  open: false,
  // 弹出层标题
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: globalHeaders(),
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/core/classes/import'
});
const uploadRef = ref<ElUploadInstance>();

const initFormData: ClassesForm = {
  deptId: undefined,
  grade: undefined,
  startYear: undefined,
  className: undefined,
}
const data = reactive<PageData<ClassesForm, ClassesQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    id: undefined,
    deptId: undefined,
    grade: undefined,
    startYear: undefined,
    className: undefined,
    params: {
    }
  },
  rules: {
    deptId: [
      { required: true, message: "学校不能为空", trigger: "change" }
    ],
    grade: [
      { required: true, message: "年级不能为空", trigger: "blur" }
    ],
    startYear: [
      { required: true, message: "开始年度不能为空", trigger: "blur" }
    ],
    className: [
      { required: true, message: "班级名称不能为空", trigger: "blur" }
    ],
  }
});
/** 调用数据模块*/ 
import { listDept } from '@/api/system/dept'; //学校
import { DeptVO } from '@/api/system/dept/types'; //学校

const { queryParams, form, rules } = toRefs(data);
// 学校
interface DeptOptionsType {
  deptId: number | string;
  deptName: string;
  children: DeptOptionsType[];
}
const deptOptions = ref<DeptOptionsType[]>([]);  

//学校改租户数据
import { useTenantlList } from '@/composables/useSchoolList';
const { tenantOptions, fetchTenantlList,tenantDisabled} = useTenantlList();
import useUserStore from '@/store/modules/user';
const userStore = useUserStore();
const userId = ref(userStore.userId);
const tenantId = ref(userStore.tenantId)

  import { listSubject, getSubject, delSubject, addSubject, updateSubject } from '@/api/core/subject'; //学科
  import { SubjectVO, SubjectQuery, SubjectForm } from '@/api/core/subject/types'; //学科
// 学科
interface SubjectType {
  deptId: number | string;
  deptName: string;
  children: SubjectType[];
}
const deptOptions_subject = ref<SubjectType[]>([]);   //学科
// 
/** 查询学科列表 */
const  getSubjectNameList = async () => {
  const res = await listSubject();
  const data = proxy?.handleTree<SubjectType>(res.data, 'deptId');
  if (data) {
    deptOptions_subject.value = data;
  }
}
getSubjectNameList()

/** 导入按钮操作 */
const handleImport = () => {
  upload.title = '学生导入';
  upload.open = true;
};
// /** 下载模板操作 */
// const importTemplate = () => {
//   proxy?.download('system/user/importTemplate', {}, `user_template_${new Date().getTime()}.xlsx`);
// };
/**文件上传中处理 */
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response: any, file: UploadFile) => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value?.handleRemove(file);
  ElMessageBox.alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', '导入结果', {
    dangerouslyUseHTMLString: true
  });
  getList();
};

/** 提交上传文件 */
function submitFileForm() {
  uploadRef.value?.submit();
}

/** 查询班级管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listClasses(queryParams.value);
  classesList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  classesFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: ClassesVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = async (row?: DeptVO) => {
  reset();
  const res = await listDept();
  const data = proxy?.handleTree<DeptOptionsType>(res.data, 'deptId');
  if (data) {
    deptOptions.value = data;
    if (row && row.deptId) {
      form.value.deptId = row?.deptId;
    }
    dialog.visible = true;
    dialog.title = "新增班级";
  }
};
/** 修改按钮操作 */
const handleUpdate = async (row?: ClassesVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getClasses(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "编辑班级";
}

/** 提交按钮 */
const submitForm = () => {
  classesFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      //如果当前登录用户是管理员，学校用选择字段；
      if(userId.value === 1 && tenantDisabled.value){

      }else{ 
        //是租户，学校默认传当前用户tenantId
        form.value.deptId = tenantId;
      }
      if (form.value.id) {
        await updateClasses(form.value).finally(() =>  buttonLoading.value = false);
        proxy?.$modal.msgSuccess("编辑成功");
      } else {
        await addClasses(form.value).finally(() =>  buttonLoading.value = false);
        proxy?.$modal.msgSuccess("编辑成功");
      }
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: ClassesVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除班级管理编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delClasses(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('core/classes/export', {
    ...queryParams.value
  }, `classes_${new Date().getTime()}.xlsx`)
}

/** 查询学校列表 */
const  getSchoolList = async () => {
  const res = await listDept();
  const data = proxy?.handleTree<DeptOptionsType>(res.data, 'deptId');
  if (data) {
    deptOptions.value = data;
  }
}
onMounted(() => {
  getList();
  getSchoolList()
});
</script>
